<?php
/**
 * Created by PhpStorm.
 * User: Wu Ning
 * Date: 2018/5/20
 * Time: 16:55
 */
namespace App\Model\Backstage;
use App\Model\Account\SystemType;
use App\Model\Base;
use Illuminate\Support\Facades\DB;
class RoomFollow extends Base
{
    public $table;
    public $customer_follow_source;
    public $room_table;
    public $room_wordbook_table;
    public function __construct()
    {
        parent::__construct();
        $this->table = 'follow_'.$this->branch_id;
//        $this->table = 'follow';

        $this->customer_follow_source = 'customer_follow_source_'.$this->branch_id;  //房、客源 跟进提醒表
//        $this->customer_follow_source = 'customer_follow_source';

         $this->room_table = 'room_info_'.$this->branch_id;
//        $this->room_table = 'room_info';


         $this->room_wordbook_table = 'room_wordbook_'.$this->branch_id; //楼盘字典
//        $this->room_wordbook_table = 'room_wordbook';



    }

    /*
     * 添加房源跟进
     * Wu Ning
     */
    public function addRoomFollow($params,$customerId = 0)
    {
        if(isset($params['cfs_remind_time']) && $params['cfs_remind_time'] != ''){
            $params['cfs_remind_time'] = strtotime($params['cfs_remind_time']);
        }
        return DB::table($this->table)
             ->insertGetId([
                'f_room_id'=>$params['f_room_id'],
                'f_follow_up_way'=>$params['f_follow_up_way'],
                'f_department_id'=>$params['f_department_id'],
                'f_user_id'=>$params['f_user_id'],
                'f_customers_id'=> $customerId,
                'f_content'=>$params['f_content'],
                 'cfs_reminder_range' => $params['cfs_user_id'],
                 'cfs_remind_time' => $params['cfs_remind_time'],
                 'cfs_content' => $params['cfs_content'],
                'f_created_at' => time(),
                'f_update_at' => time()
         ]);
    }

    /**
     * 修改房源跟进
     */
    public function updateFollow($params){
        DB::beginTransaction();//开启事务
        $roomData = DB::table($this->table)->where('f_id',$params['f_id'])->select('f_room_id','cfs_reminder_range')->first();
        if ($params['cfs_remind_time'] == "") {
            $params['cfs_user_id'] = 0;
            $params['cfs_content'] = '';
            $del = true;
            $cfs_id = true;
        } else{
            $del = true;
            if (intval($roomData->cfs_reminder_range) != 0 && intval($roomData->cfs_reminder_range) != intval($params['cfs_user_id'])) {
                //删除之前的跟进提醒
                $del = DB::table($this->customer_follow_source)->where('cf_id',$params['f_id'])->delete();
            }
            $params['f_room_id'] = $roomData->f_room_id;
            $params['cfs_type'] = 1;
            $customerfollowsourde =  new CustomerFollowSourde();
            $cfs_id =  $customerfollowsourde->addCustomerFollowSourde($params,$params['f_id']);

        }

        $updateResult = DB::table($this->table)
            ->where('f_id',$params['f_id'])
            ->update([

                'f_follow_up_way'=>$params['f_follow_up_way'],
                'f_user_id'     =>$params['f_user_id'],
                'f_department_id'=>$params['f_department_id'],
                'f_content'     =>$params['f_content'],
                'f_customers_id'  =>$params['f_customers_id'],
                'cfs_remind_time'       => strtotime($params['cfs_remind_time']),
                'cfs_content'           => $params['cfs_content'],
                'cfs_manager_review'    => $params['cfs_manager_review'],
                'cfs_reminder_range'    => $params['cfs_user_id'],
                'f_update_at' =>time()
            ]);

        //更新房源跟进时间
        $updateFollowtime = DB::table($this->room_table)->where('id',$roomData->f_room_id)->update([
            'r_follow_time'=>time()
        ]);
       if($updateResult && $updateFollowtime && $del && $cfs_id){
           DB::commit();
            return true;
        }
        DB::rollback();//失败回滚
        return false;

    }


    /**
     * @param array $map
     * @param $pageLimit
     * @return mixed
     * 获取用户房源跟进数量排行
     * author:lxy
     */
    public function getRoomFollowNum($map =[], $where = []){
        $user_list = DB::table('user')
            ->leftJoin('department', 'u_d_id', '=', 'id')
            ->where('u_b_id', $this->branch_id)
            ->where($where)
            ->where('u_status', 1)
            ->where('user.is_del', 0)
            ->select(['u_id','u_username','name'])
            ->get()
            ->toArray();
        foreach($user_list as $k => $v){
            $num = DB::table($this->table)->where($map)->where('f_user_id', $v->u_id)->count();
            $v->num = $num;
        }
        $list = json_encode($user_list);
        $list = json_decode($list,true);
        array_multisort(array_column($list,'num'),SORT_DESC,$list);
        return $list;
    }

    /**
     * @param $roomInfoModel
     * @param $params
     * @return mixed
     * 移动员工房源跟进
     */
    public function moves($roomInfoModel, $params){
        $room_ids = $roomInfoModel->moves($params, 2);
        return DB::table($this->table)
            ->whereIn('f_room_id', $room_ids)
            ->update([
                'f_user_id'   => $params['to_uid'],
                'f_update_at' => time(),
            ]);
    }

    /**某个房源的跟进列表
     * @param $roomId 房源DI
     * @param $pageLimit
     * @param $pcOrApp  pc传0   APP传1
     * @return bool
     */
    public function roomFollow($roomId,$pageLimit, $pcOrApp){
        if ($pcOrApp == 0) {//PC
            $list = DB::table($this->table)
                ->leftJoin('user', 'f_user_id', '=', 'u_id')
                ->leftJoin('department', 'f_department_id', '=', 'id')
                ->where('f_room_id',$roomId)
                ->select('f_id','f_room_id','f_follow_up_way', 'u_username', 'name','f_content',
                    DB::raw('from_unixtime(f_created_at) as f_created_at'), 'f_created_at as created_at',
                    'cfs_reminder_range as cfs_user_id', 'cfs_remind_time', 'cfs_content', 'cfs_manager_review')
                ->orderBy('f_id', 'desc')
                ->paginate($pageLimit);
        } else {//APP
            $list = DB::table($this->table)
                ->leftJoin('user', 'f_user_id', '=', 'u_id')
                ->leftJoin('department', 'f_department_id', '=', 'id')
                ->where('f_room_id',$roomId)
                ->select('f_id','f_room_id','f_follow_up_way', 'u_username', 'name','f_content',
                    DB::raw('from_unixtime(f_created_at) as f_created_at'), 'f_created_at as created_at',
                    'cfs_reminder_range as cfs_user_id', 'cfs_remind_time', 'cfs_content', 'cfs_manager_review')
                ->orderBy('f_id', 'desc')
                ->paginate($pageLimit);
        }

        if (sizeof($list) == 0) {
            return $list;
        }
        foreach ($list as $k => $v) {
                $v->type = 1;
            if ($v->cfs_remind_time) {
                $v->cfs_remind_time = date('Y-m-d H:i:s', $v->cfs_remind_time);
            } else {
                $v->cfs_remind_time = '';
            }
            if ($v->cfs_user_id =! 0) {
                $v->cfs_user_id = $v->cfs_user_id == 1 ? '本人' : '本部' ;
            } else {
                $v->cfs_user_id = '';
            }
        }
        return $list;
    }

    /**
     * 删除房源跟进
     */
    public function delFollow($followId){
        DB::table($this->customer_follow_source)
            ->where('cf_id', $followId)
            ->where('cfs_type',1)
            ->delete();
        return DB::table($this->table)->where('f_id', $followId)->delete();
    }


    /**所有房源的跟进列表
     * @param $where
     * @param $pageLimit
     * @return bool  env('PAGE_LIMIT_ADMIN'), $where, $keywords
     */
    public function listFollow($pageLimit, $where = [], $keywords)
    {
        if ($keywords == '') {
            $list = DB::table($this->table)
                ->leftJoin($this->room_table, $this->room_table.'.id', '=', 'f_room_id')
                ->leftJoin($this->room_wordbook_table, 'building_id', '=', 'w_id')
                ->leftJoin('user', 'f_user_id', '=', 'u_id')
                ->leftJoin('department', 'f_department_id', '=', 'department.id')
                ->where($where)
                //跟进时间、 跟进人部门   跟进人  方式
                //  房源编号  楼盘字典  栋座 位置  交易类型 状态  跟进内容
                    //提醒日   提醒内容   被提醒人      经理点评
                ->select('f_id', 'f_room_id', DB::raw('from_unixtime(f_created_at) as f_created_at'), 'name', 'u_username', 'f_follow_up_way',
                    'property_number', 'w_name', 'few_building', 'position', 'trading_type', 'status', 'f_content','f_department_id','f_user_id',
                   'cfs_reminder_range','cfs_remind_time','cfs_content','cfs_manager_review' )
                ->orderBy('f_id', 'desc')
                ->paginate($pageLimit);
        } else {
            //跟进的内容    房源的编号  业主姓名   业主电话

                $list = DB::table($this->table)
                    ->leftJoin($this->room_table, $this->room_table.'.id', '=', 'f_room_id')
                    ->leftJoin($this->room_wordbook_table, 'building_id', '=', 'w_id')
                    ->leftJoin('user', 'f_user_id', '=', 'u_id')
                    ->leftJoin('department', 'f_department_id', '=', 'department.id')
                ->where(function ($query) use($where, $keywords){
                    $query->where($where)->where('f_content', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords) {
                    $query->where($where)->where('owner_name', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('owner_phone', 'like', '%'.$keywords.'%');
                })->orWhere(function ($query) use($where, $keywords){
                    $query->where($where)->where('property_number', 'like', '%'.$keywords.'%');
                })
                    ->select('f_id', 'f_room_id', DB::raw('from_unixtime(f_created_at) as f_created_at'), 'name', 'u_username', 'f_follow_up_way',
                        'property_number', 'w_name', 'few_building', 'position', 'trading_type', 'status', 'f_content','f_department_id','f_user_id',
                        'cfs_reminder_range','cfs_remind_time','cfs_content','cfs_manager_review')
                ->orderBy('f_id', 'desc')
                ->paginate($pageLimit);
        }

        if (sizeof($list) == 0) {
            return false;
        }
        foreach($list as $k=>$v){
            if($v->cfs_remind_time != 0){
                $v->cfs_remind_time = date('Y-m-d',$v->cfs_remind_time);
            }else{
                $v->cfs_remind_time = '';
            }
            if($v->cfs_reminder_range != 0){
                $v->cfs_name = $v->cfs_reminder_range == 1 ? '本人': '本部';
            }else{
                $v->cfs_name = '';
            }

            $v->trading_type = SystemType::getTypeDetail($v->trading_type);//交易类型
            $v->status = SystemType::getTypeDetail($v->status); //交易状态类型
        }
        return $list;
    }

    /**
     * 根据房源ID、员工ID  查询当天该员工有没有对该房源写过跟进
     */
    public function getFollowDay($rid, $uid)
    {
        //根据最后的跟进时间计算出 那天的结束时间
        $f_created_at = DB::table($this->table)->where('f_room_id', $rid)->where('f_user_id', $uid)->orderBy('f_id', 'desc')->value('f_created_at');
        $fTime = intval(strtotime(date('Y-m-d', $f_created_at).' 23:59:59'));
        //当天的结束时间
        $nowTime = intval(strtotime(date('Y-m-d', time()).' 23:59:59'));
        //最后跟进的天  不是今天的话
        if ($fTime != $nowTime) {
            return 2;
        }
        return 1;
    }
}